//
//  ST_DTBootManager.swift
//  BTVideo
//
//  Created by DouLei on 23/01/2019.
//  Copyright © 2018 DouLei. All rights reserved.

import UIKit
import SwifterSwift
import RealmSwift
import SwiftyUserDefaults
import IQKeyboardManagerSwift
import NIMSDK
//import KeychainAccess
import SDWebImage
import DeviceKit
import SwiftyUserDefaults
import SwiftyJSON
import StoreKit
import RxCocoa
import RxSwift
import AlamofireNetworkActivityLogger
import KTVHTTPCache
#if DEBUG
import GDPerformanceView_Swift
#endif




class ST_DTBootManager:NSObject {
    
    static let shared = ST_DTBootManager()
    
    
    // Can't init is singleton
    private override init() {
        super.init()
    }
    
    /**
     启动时间
     */
    private(set) var bootDate = Date()
    

    /**
     当前展示登录页
     */
    var isDisplayLoginKeyWindow:Bool{
        if UIApplication.shared.delegate?.window??.rootViewController is ST_BTBootController{
            return false
        }
        return true
    }
    
    
    @objc static func manager() -> ST_DTBootManager {
        return ST_DTBootManager.shared
    }
    
    fileprivate(set) lazy var wxHandler = ST_BootWeChatHandle()
    
    fileprivate(set) lazy var qqHandler = ST_BootQQApiHandle()
    
    /**
     是否加载广告页
     */
    fileprivate(set) var displayAdvert:Bool?
}


extension ST_DTBootManager{
    
    private func binding(){
        
        Defaults.rx.observe(Bool.self, DefaultsKeys.agreeLicense._key).compactMap{$0}.withUnretained(self).subscribe(onNext: { own, agree in
            
            if agree == true{
                
                SCComponets.start()
                
                self.third_libraries_config()
                
//                //TIANPayManager.shared.startListening()
                //                语音房已经取消了
//                TIANChatGroupManager.defaultManager.startListening()
            
                /// RS 启动上报   等待基础接口请求完毕
                SCComponets.config_component.boot_config_observer.subscribe(onNext: { status in
                    if status == .finished {
                        ST_EngagementCentServer.shared.startListening()
                    }
                }).disposed(by: own.rx.disposeBag)
            }
            
        }).disposed(by: rx.disposeBag)
        
        
        Defaults.rx.observe(Bool.self, DefaultsKeys.BTLoginSuccess._key).distinctUntilChanged().subscribe(onNext: { f in
            
            let appDelegate = UIApplication.shared.delegate
         
            if let login = f,login == true{
                
                if self.displayAdvert == nil {
                    self.displayAdvert = true
                }
                ST_BTLaunchController.shared.scroll_to_page(tab: .recommend)
                
                appDelegate?.window??.rootViewController = ST_BTBootController.shared
                
                appDelegate?.window??.makeKeyAndVisible()
                
            }else{
                
                self.displayAdvert = false
                
                appDelegate?.window??.rootViewController = ST_RegisterMonitor.shared.login_root_controller_generator()
                
                appDelegate?.window??.makeKeyAndVisible()
                
            }
            
        }).disposed(by: rx.disposeBag)
        
        
    }

    private func app_appearance() {
        
//        UIApplication.shared.setStatusBarOrientation(UIInterfaceOrientation.portrait, animated: false)
        UITabBar.appearance().backgroundColor = Color.white
        UITextField.appearance().tintColor = Color.white
        UITextView.appearance().tintColor = Color.white
        UITableViewCell.appearance().backgroundColor = .clear
//        if #available(iOS 15.0, *) {
//            UITableView.appearance().sectionHeaderTopPadding = 0
//        }
    }
    
    
    
    private func third_libraries_config() {
        
        print("采集用户设备信息 ThirdLibrariesConfig")
        
        //#####        添加 Crashlytics
        //        Fabric.with([Crashlytics.self])
        //        Bugly.start(withAppId: "247de764cd")
        
        let keyboardManager = IQKeyboardManager.shared
        keyboardManager.enable = true
        //        keyboardManager.enableDebugging = true
        
        keyboardManager.disabledDistanceHandlingClasses.append(ST_PrivateChatViewController.self)
        keyboardManager.disabledToolbarClasses.append(ST_PrivateChatViewController.self)
        
        
        keyboardManager.disabledDistanceHandlingClasses.append(ST_EditMyIntroViewController.self)
        keyboardManager.disabledToolbarClasses.append(ST_EditMyIntroViewController.self)
        
        
        keyboardManager.disabledDistanceHandlingClasses.append(ST_PeculiarityGroupViewController.self)
        keyboardManager.disabledToolbarClasses.append(ST_PeculiarityGroupViewController.self)
        
        
        keyboardManager.disabledDistanceHandlingClasses.append(ST_CommentListViewController.self)
        keyboardManager.disabledToolbarClasses.append(ST_CommentListViewController.self)
        
        
        keyboardManager.disabledDistanceHandlingClasses.append(ST_DarkST_CommentListViewController.self)
        keyboardManager.disabledToolbarClasses.append(ST_DarkST_CommentListViewController.self)
        
        
        
        keyboardManager.disabledDistanceHandlingClasses.append(ST_RecommendPecVideoController.self)
        keyboardManager.disabledToolbarClasses.append(ST_RecommendPecVideoController.self)
        
        keyboardManager.disabledToolbarClasses.append(ST_QuickMessageTextViewController.self)
        
        //        友盟统计
        back_thread_execute {
            self.u_m_cofing_instace()
        }
        
        qqHandler.start_tencent_o_auth()
        
        /*
         //在register之前打开log, 后续可以根据log排查问题
         WXApi.startLog(by: WXLogLevel.detail) { (str) in
         print("WeChatSDK: ",str)
         }
         */
        
        //务必在调用自检函数前注册
        WXApi.registerApp("***", universalLink: "***")
        
        /*
         //调用自检函数
         WXApi.checkUniversalLinkReady { (step, result) in
         print("微信 自动检测--step:", step.rawValue, "--success:",result.success,"--errorInfo:" ,result.errorInfo, "----suggestion:",result.suggestion);
         }
         */
        
        //        高德地图
        AMapServices.shared().apiKey = "***"
        
        print("Finished ThirdLibrariesConfig")
        
        //        IM
        
        NIMSDK.shared().register(withAppID: PH.nimAppID, cerName: "***")
        
        NIMSDKConfig.shared().shouldConsiderRevokedMessageUnreadCount = true
        
        NIMSDKConfig.shared().asyncLoadRecentSessionEnabled = true
        
        NIMCustomObject.registerCustomDecoder(ST_BTMessageAttachDecoder())
       
        
        //        SDImageCache.shared.config.maxMemoryCost = 8 * 1024 * 1024
            #if DEBUG
                    NetworkActivityLogger.shared.level = .debug
                    NetworkActivityLogger.shared.startLogging()
            #endif
        
        setup_h_t_t_p_cache()
        
    }
    
    private func data_base_configuration(){
        
        let config = Realm.Configuration(
            
            schemaVersion: 343,
            
            migrationBlock: { migration, oldSchemaVersion in
                // We haven’t migrated anything yet, so oldSchemaVersion == 0
//                if (oldSchemaVersion < 260) {
//
//                    migration.enumerateObjects(ofType: ST_BTUserinfo.className()) { (oldObject, newObject) in
//
//                        let coinInt = oldObject?["sweet_coin"] as? Int
//
//                        newObject?["sweet_coin"] = coinInt?.float ?? 0
//                    }
//
//                }
        })
        
        // Tell Realm to use this new configuration object for the default Realm
        Realm.Configuration.defaultConfiguration = config
        
        // Now that we've told Realm how to handle the schema change, opening the file
        // will automatically perform the migration
        _ = try! Realm()
    }
    
    private func app_settings()  {
        
        ST_NetworkStatusManager.shared.start_network_reachability_observer()
        
        app_appearance()
        
    }
    
    //友盟统计
    private func  u_m_cofing_instace() {
      
        UMConfigure.initWithAppkey("***", channel: "")
        /*
         let  config =  UMAnalyticsConfig.init()
         config.appKey = "5b95d8aaa40fa3394e000127"
         MobClick.start(withConfigure: config)
         MobClick.setLogEnabled(true)
         */
    }
    
    private func setup_h_t_t_p_cache(){
            
        KTVHTTPCache.logSetConsoleLogEnable(false)
        do{
            try KTVHTTPCache.proxyStart()
            
            KTVHTTPCache.encodeSetURLConverter { (url) -> URL? in
                
//                print("缓存方案 URL Filter reviced URL :\(String(describing: url))")
                
                return url
            }
            
            KTVHTTPCache.downloadSetUnacceptableContentTypeDisposer { (url, contentType) -> Bool in
                
                
                
                return false
            }
            
            
        }catch{
            print("缓存方案 Proxy Start Failure:",error)
        }
        
        
        
    }
}


extension ST_DTBootManager{
    
    func normal_run(){
        
        ST_TIANRouteMonitor.default.start()
        
        data_base_configuration()
        
        app_settings()
        
        binding()
        
        #if DEBUG
            PerformanceMonitor.shared().start()
        #endif
        
    }
    
    func authorize_q_q() {
        qqHandler.authorize_q_q()
    }
}
